package com.login.client.utils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

public class HttpParamUtil {

    /**
     * 构建URL编码的form-data参数字符串
     *
     * @param params 参数Map，有序推荐使用LinkedHashMap
     * @return application/x-www-form-urlencoded格式字符串
     */
    public static String buildFormData(Map<String, Object> params) {
        StringBuilder formData = new StringBuilder();
        try {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (formData.length() > 0) {
                    formData.append("&");
                }

                // 类型安全处理
                String encodedValue;
                if (entry.getValue() instanceof String) {
                    encodedValue = encodeString((String) entry.getValue());
                } else if (entry.getValue() instanceof Number ||
                        entry.getValue() instanceof Boolean) {
                    encodedValue = encodeString(entry.getValue().toString());
                } else if (entry.getValue() == null) {
                    encodedValue = "";
                } else {
                    throw new IllegalArgumentException(
                            "Unsupported parameter type: " + entry.getValue().getClass().getName());
                }

                formData.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                        .append("=")
                        .append(encodedValue);
            }
        } catch (Exception e) {
            throw new RuntimeException("参数编码失败", e);
        }
        return formData.toString();
    }


    /**
     * 快速构建OAuth2 token请求参数
     */
    public static String buildOAuth2TokenParams(String grantType, String code, String clientId, String clientSecret) {
        Map<String, Object> params = new LinkedHashMap<>(4);
        params.put("grant_type", grantType);
        params.put("code", code);
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        return buildFormData(params);
    }

    private static String encodeString(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8);
    }
}